// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

// Non-Nebula system benchmarks, provided for convenience.

#include <algorithm>
#include <cstdint>
#include <limits>
#include <random>
#include <string>
#include <vector>

#include <benchmark/benchmark.h>

namespace nebula {

#ifdef NEBULA_WITH_BENCHMARKS_REFERENCE

// Generate a vector of indices such as following the indices describes
// a path over the whole vector.  The path is randomized to avoid triggering
// automatic prefetching in the CPU.
std::vector<int32_t> RandomPath(int32_t size) {
  std::default_random_engine gen(42);
  std::vector<int32_t> indices(size);

  for (int32_t i = 0; i < size; ++i) {
    indices[i] = i;
  }
  std::shuffle(indices.begin(), indices.end(), gen);
  std::vector<int32_t> path(size, -999999);
  int32_t prev;
  prev = indices[size - 1];
  for (int32_t i = 0; i < size; ++i) {
    int32_t next = indices[i];
    path[prev] = next;
    prev = next;
  }
  return path;
}

// Cache / main memory latency, depending on the working set size
static void memory_latency(benchmark::State& state) {
  const auto niters = static_cast<int32_t>(state.range(0));
  const std::vector<int32_t> path = RandomPath(niters / 4);

  int32_t total = 0;
  int32_t index = 0;
  for (auto _ : state) {
    total += index;
    index = path[index];
  }
  benchmark::DoNotOptimize(total);
  state.SetItemsProcessed(state.iterations());
}

BENCHMARK(memory_latency)->Repetitions(1)->RangeMultiplier(2)->Range(2 << 10, 2 << 24);

#endif  // NEBULA_WITH_BENCHMARKS_REFERENCE

}  // namespace nebula
